package cn.t.service.user;


import cn.t.core.enums.base.BaseStatusEnum;
import cn.t.core.exception.BizException;
import cn.t.core.mode.YesNoEnum;
import cn.t.core.service.ServiceImpl;
import cn.t.core.enums.base.CommonError;
import cn.t.enums.user.ScenarioCodeEnum;
import cn.t.model.user.CostCenterDO;
import cn.t.model.user.CustomerFirmDO;
import cn.t.model.user.ParticipantInfoDO;
import cn.t.model.user.UserInfoDO;
import cn.t.repository.user.ParticipantInfoRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;

/**
 * 参与者信息表领域服务
 *
 * @author l
 */
@Slf4j
@Service
@AllArgsConstructor
public class ParticipantInfoService extends ServiceImpl<ParticipantInfoDO, ParticipantInfoRepository> {

    public void deleteParticipantByUserId(Long userId) {
        repository.deleteParticipantByUserId(userId);
    }

    public List<ParticipantInfoDO> findByUserId(Long userId) {

        ParticipantInfoDO template = new ParticipantInfoDO();
        template.setUserId(userId);
        template.setStatus(String.valueOf(BaseStatusEnum.AVAILABLE.getCode()));

        return repository.findByModel(template, 0, 10000, "id", "asc");
    }


    public List<ParticipantInfoDO> findByUserIdIgnoreDisable(Long userId) {
        ParticipantInfoDO template = new ParticipantInfoDO();
        template.setUserId(userId);
        template.setStatus(String.valueOf(BaseStatusEnum.DISABLE.getCode()));

        return repository.findByModel(template, 0, 10000, "id", "asc");
    }

    public void disableByUserId(Long userId) {
        repository.disableByUserId(userId);
    }

    public void isValidParticipant(ParticipantInfoDO participantInfo, UserInfoDO userInfo, CustomerFirmDO customerFirm) {
        ParticipantInfoDO participantFromDb = findById(participantInfo.getId());
        if (participantFromDb == null
                || !participantFromDb.getId().equals(participantInfo.getId())
                || !participantInfo.getUserId().equals(userInfo.getId())
                || (customerFirm != null && !customerFirm.getId().equals(participantFromDb.getFirmId()))) {
            String errorMessage = String.format("指定的用户不存在 participantId=%s ", participantInfo.getId());
            log.error(errorMessage);
            throw new BizException(CommonError.ILLEGAL_PARAMETER, errorMessage);

        }
    }

    public List<ParticipantInfoDO> findByIds(Set<Long> existsParticipantIds) {
        ParticipantInfoDO template = new ParticipantInfoDO();
        template.setParticipantIds(existsParticipantIds);
        template.setStatus(String.valueOf(BaseStatusEnum.AVAILABLE.getCode()));

        return repository.findByModel(template, 0, 10000, "id", "asc");
    }

    public List<ParticipantInfoDO> findByUserFirm(Long userId, Long firmId) {

        ParticipantInfoDO template = new ParticipantInfoDO();
        template.setUserId(userId);
        template.setFirmId(firmId);
        template.setStatus(String.valueOf(BaseStatusEnum.AVAILABLE.getCode()));

        return repository.findByModel(template, 0, 10000, "id", "asc");
    }

    public ParticipantInfoDO getOrAdd(Long userId, Long individualId, Long firmId) {
        ParticipantInfoDO template = new ParticipantInfoDO();
        template.setFirmId(firmId);
        template.setUserId(userId);
        template.setIndividualId(individualId);
        template.setStatus(String.valueOf(BaseStatusEnum.AVAILABLE.getCode()));
        template.setIsDeleted(YesNoEnum.FALSE);

        List<ParticipantInfoDO> tmp = repository.findByModel(template, 0, 1, "id", "asc");
        if (CollectionUtils.isEmpty(tmp)) {
            template.setScenarioId(ScenarioCodeEnum.PLATFORM_OPERATION.getCode());
            Long id = repository.addAndReturnId(template);
            template.setId(id);
            return template;
        }

        return tmp.get(0);
    }


    public ParticipantInfoDO getOrAddByCostCenter(Long userId, Long individualId, Long costCenterId) {
        CostCenterDO costCenterDO = costCenterService.findById(costCenterId);
        if (costCenterDO == null) {
            String errorMessage = String.format("指定的成本中心不存在 costCenterId=%d ", costCenterId);
            log.error(errorMessage);
            throw new BizException(CommonError.ILLEGAL_PARAMETER, errorMessage);
        }

        ParticipantInfoDO template = new ParticipantInfoDO();

        template.setFirmId(costCenterDO.getFirmId());
        template.setUserId(userId);
        template.setIndividualId(individualId);
        template.setStatus(String.valueOf(BaseStatusEnum.AVAILABLE.getCode()));
        template.setIsDeleted(YesNoEnum.FALSE);

        List<ParticipantInfoDO> tmp = repository.findByModel(template, 0, 1, "id", "asc");
        if (CollectionUtils.isEmpty(tmp)) {
            template.setScenarioId(ScenarioCodeEnum.PLATFORM_OPERATION.getCode());
            template.setCostCenterId(costCenterId);
            Long id = repository.addAndReturnId(template);
            template.setId(id);
            return template;

        } else if (!costCenterId.equals(tmp.get(0).getCostCenterId())) {

            tmp.get(0).setCostCenterId(costCenterId);
            repository.update(tmp.get(0));
        }

        return tmp.get(0);

    }

    public ParticipantInfoDO findByUserCostCenter(Long userId, Long costCenterId) {
        ParticipantInfoDO template = new ParticipantInfoDO();

        template.setCostCenterId(costCenterId);
        template.setUserId(userId);
        template.setStatus(String.valueOf(BaseStatusEnum.AVAILABLE.getCode()));
        template.setIsDeleted(YesNoEnum.FALSE);

        List<ParticipantInfoDO> tmp = repository.findByModel(template, 0, 1, "id", "asc");
        if (CollectionUtils.isEmpty(tmp)) {
            return null;
        }
        return tmp.get(0);
    }

    public void clearCostCenter(Long userId) {
        repository.clearCostCenter(userId);
    }

    public void disableParticipantByUserId(Long userId) {
        repository.disableParticipantByUserId(userId);
    }

    public void enableParticipantByUserId(Long userId) {
        repository.enableParticipantByUserId(userId);
    }

    public void unbindCostCenter(Long id) {
        repository.unbindCostCenter(id);
    }

    @Autowired
    private CostCenterService costCenterService;



}
